import { _decorator, Component, Node } from 'cc';
import { BaseManager } from '../libs/rxjs/cc3/BaseManager';
import { director } from 'cc';
import { color } from 'cc';
import { System } from 'cc';
import { ProvideInfo } from './SDK/IapSDKManager';
import { DevConfig } from './DevConfig';
import { udm } from './UserDataManager';
import { timem } from './TimeManager';
import { thinking_sdk_m } from './SDK/ThinkingCocosSDKManager';
const { ccclass, property } = _decorator;

export type TaskInfo = {
    taskId: number,
    taskType: string,
    times: number,
    provide?: ProvideInfo,
    probability?: { provide: ProvideInfo, p: number }[]
}

@ccclass('TaskManager')
export class TaskManager extends BaseManager {

    public static instance: TaskManager;
    static ID = 'task_system';
    get logColorOverride() { return color().fromHEX('#CCEECC') };

    static registerSystem() {
        director.unregisterSystem(director.getSystem(TaskManager.ID));
        director.registerSystem(TaskManager.ID, taskm, System.Priority.MEDIUM);
        taskm.init();
    }

    onInitManager(): void {
        this.taskDailyList = Object.values(DevConfig.task.daily);
        this.taskDailyList.forEach(taskInfo => this.taskMap.set(taskInfo.taskId, taskInfo));
        this.taskMap.set(100, DevConfig.task.daily_total[100]);
        for (let [taskId, taskInfo] of this.taskMap) {
            if (!this.taskTypeToTaskIds.has(taskInfo.taskType)) {
                this.taskTypeToTaskIds.set(taskInfo.taskType, new Set());
            }
            let taskIds = this.taskTypeToTaskIds.get(taskInfo.taskType);
            taskIds.add(taskId);
        }

        this.checkInc('daily_task');
    }

    taskDailyList: TaskInfo[] = [];

    taskMap = new Map<number, TaskInfo>();

    taskTypeToTaskIds = new Map<string, Set<number>>();

    getTaskCurrentTimes(taskId: number) {
        return udm.task.value[taskId] ?? 0
    }

    refreshStorage() {
        let needClearAt = new Date(udm.taskUpdateAt.value);
        needClearAt.setHours(24, 0, 0, 0);
        if (timem.now() > needClearAt.valueOf()) {
            this.resetDaily();
        }
    }

    resetDaily() { // 重置每日
        this.taskDailyList.forEach(taskInfo => delete udm.task.value[taskInfo.taskId]);
        delete udm.task.value[100];
        udm.task.again();
        udm.taskUpdateAt.value = timem.now();
        udm.save();
    }

    incTimes(taskId: number, inc = 1) {
        this.refreshStorage();
        if (udm.task.value == null) udm.task.value = {};
        if (udm.task.value[taskId] == null) udm.task.value[taskId] = 0;
        if (this.getTaskCurrentTimes(taskId) == -1) return; // 已经领取的不继续统计次数
        let taskInfo = this.taskMap.get(taskId);
        udm.task.value[taskId] = Math.min(taskInfo.times, udm.task.value[taskId] + inc); // 封顶

        // this.checkInc('daily_task');// 不在达到的时候计算了

        udm.task.again();
        udm.taskUpdateAt.value = timem.now();
        udm.save();
    }

    claim(taskId: number) {
        let taskInfo = this.taskMap.get(taskId);
        if (this.getTaskCurrentTimes(taskId) >= taskInfo.times) { // 可以claim
            udm.task.value[taskId] = -1; // -1表示已领取
            udm.task.again();
            if (taskInfo.provide != null) {
                udm.provide(taskInfo.provide);
                this.thinking(taskInfo.provide, 'DailyTask');
            }
            this.checkInc('daily_task');
        }
    }

    checkInc(taskType: string) { // 在对应的位置埋下此点
        if (taskType == 'daily_task') {
            let times = [101, 102, 103, 104].map(_ => (this.getTaskCurrentTimes(_) == -1 ? 1 : 0) as number).reduce((p, c) => {
                return p + c;
            });
            udm.task.value[100] = times;
        } else {
            let ids = this.taskTypeToTaskIds.get(taskType)
            ids.forEach(taskId => {
                this.incTimes(taskId);
            });
        }
    }

    thinking(provide: ProvideInfo, type: string) {
        if (provide.coin > 0) {
            thinking_sdk_m.requestTrack('Coins_Get', {
                CoinNum: provide.coin,
                Type: type,
                Gift_Detail: 'Other',
                IsNew: udm.isNew.value,
                Level_ID: udm.stageNum.value,
                Booster_Itemdetail: `Swapper:${udm.itemSwapper.value}|Magnet:${udm.itemMagnet.value}|Balloon:${udm.itemBalloon.value}`
            });
        } else if (provide.swapper > 0) {
            thinking_sdk_m.requestTrack('Item_Get', {
                ItemType: 'swapper',
                CType: type,
                UseType: 'Num',
                ItemNum: provide.swapper,
                ItemAll: udm.itemSwapper.value,
                Level_ID: udm.stageNum.value,
                IsNew: udm.isNew.value,
                Booster_Itemdetail: `Swapper:${udm.itemSwapper.value}|Magnet:${udm.itemMagnet.value}|Balloon:${udm.itemBalloon.value}`
            });
        } else if (provide.magnet > 0) {
            thinking_sdk_m.requestTrack('Item_Get', {
                ItemType: 'magnet',
                CType: type,
                UseType: 'Num',
                ItemNum: provide.magnet,
                ItemAll: udm.itemMagnet.value,
                Level_ID: udm.stageNum.value,
                IsNew: udm.isNew.value,
                Booster_Itemdetail: `Swapper:${udm.itemSwapper.value}|Magnet:${udm.itemMagnet.value}|Balloon:${udm.itemBalloon.value}`
            });
        } else if (provide.balloon > 0) {
            thinking_sdk_m.requestTrack('Item_Get', {
                ItemType: 'balloon',
                CType: type,
                UseType: 'Num',
                ItemNum: provide.balloon,
                ItemAll: udm.itemBalloon.value,
                Level_ID: udm.stageNum.value,
                IsNew: udm.isNew.value,
                Booster_Itemdetail: `Swapper:${udm.itemSwapper.value}|Magnet:${udm.itemMagnet.value}|Balloon:${udm.itemBalloon.value}`
            });
        }
        // TODO: 如果宝箱里面有体力的奖励，也应该在此补充
    }
}


globalThis.TaskManager = TaskManager;

export const taskm = TaskManager.instance = new TaskManager();
